import axios from "axios"
import { ElMessage } from 'element-plus'
import 'element-plus/theme-chalk/el-message.css'
import { useUserStore } from '@/stores/user'
import router from '@/router'

// 创建axios实例
const httpInstance = axios.create({
    baseURL: 'http://pcapi-xiaotuxian-front-devtest.itheima.net', // 项目基地址
    timeout: 5000 // 超时时间
})

// 拦截器

// axios请求拦截器
httpInstance.interceptors.request.use(config => {
    // 获取token
    const userStore = useUserStore()
    const token = userStore.userInfo.token
    // 判断token是否存在
    if (token) {
        // 拼接token
        config.headers.Authorization = `Bearer ${token}`
    }
    
    return config
}, e => Promise.reject(e))
  
// axios响应式拦截器
httpInstance.interceptors.response.use(res => res.data, e => {
    const userStore = useUserStore()
    // 统一返回错误信息
    ElMessage.error(e.response.data.message)
    // 处理401 token失效
    if (e.response.status === 401) {
        // 退出登录
        userStore.removeInfo()
        router.push('/login')
    }
    return Promise.reject(e)
})

// 默认导出
export default httpInstance
